package com.ftg.learn.day11.ioc;

import com.ftg.learn.day11.Shop;

/**
 * 类的核心池
 *  泛型  ：
 *
 *  三种使用方式 ：
 *
 *  反射优点 缺点 ：
 *
 *  1 ： 工厂  代理  适配  单例 DCL
 *
 * @author 布衣
 */
public class BeanCorePool {

    private BeanInfo[] beanInfos = new BeanInfo[100];
    private int size;


    public BeanCorePool() {
    }

    /**
     * 类的注册
     */
    public void registerBean(String... beans) {
        if (null == beans) {
            throw new RuntimeException("请输入正确的类信息");
        }
        for (int i = 0; i < beans.length; i++) {
            BeanInfo bi = new BeanInfo();
            try {
                Class<? extends Object> bean = Class.forName(beans[i]);
                Object obj = bean.newInstance();
                bi.setBeanPath(beans[i]);
                bi.setClassObj(bean);
                bi.setInstance(obj);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            beanInfos[size++] = bi;
        }
    }

    /**
     * 类注入

     * @param beans 类信息
     */
    public  void registerBean(Class<? extends Object>... beans) {
        if (null == beans) {
            throw new RuntimeException("请输入正确的类信息");
        }
        for (int i = 0; i < beans.length; i++) {
            BeanInfo bi = new BeanInfo<>();
            try {
                Object obj = beans[i].newInstance();
                bi.setBeanPath(beans[i].getName());
                bi.setClassObj(beans[i]);
                bi.setInstance(obj);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            beanInfos[size++] = bi;
        }
    }

    /**
     *  * <E> : 方法泛型
     * @param c
     * @return
     * @param <E>
     */
    public <E> E getBean(Class<E> c){
        for (int i = 0; i < size; i++) {
            if (beanInfos[i].getClassObj() == c) {
                return (E)beanInfos[i].getInstance();
            }
        }
        return null;
    }

    public <E> E getBean(String classPath){
        for (int i = 0; i < size; i++) {
            if (beanInfos[i].getBeanPath().equals(classPath)) {
                return (E)beanInfos[i].getInstance();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        BeanCorePool bcp = new BeanCorePool();

        bcp.registerBean(A.class,B.class);

        A a1 = bcp.getBean(A.class);
        B b1 = bcp.getBean(B.class);

    }

}
